package common;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;

import jp.sourceforge.qrcode.QRCodeDecoder;
import jp.sourceforge.qrcode.data.QRCodeImage;

import com.swetake.util.Qrcode;

public class Qrcoding {


	public BufferedImage encoderQRCode(String content) {
		try {
			int version=20;
			Qrcode qrcodeHandler = new Qrcode();
			qrcodeHandler.setQrcodeErrorCorrect('M');
			qrcodeHandler.setQrcodeEncodeMode('B');
			qrcodeHandler.setQrcodeVersion(version);
			byte[] contentBytes = content.getBytes("UTF-8");
			BufferedImage bufferedImage = new BufferedImage(67+12*(version-1), 67+12*(version-1),BufferedImage.TYPE_INT_RGB);
			Graphics2D gs = bufferedImage.createGraphics();
			gs.setBackground(Color.WHITE);
			gs.clearRect(0, 0, 67+12*(version-1), 67+12*(version-1));
			gs.setColor(Color.BLACK);
			int pixoff = 2;

			if (contentBytes.length > 0 && contentBytes.length < 600) {
				boolean[][] codeOut = qrcodeHandler.calQrcode(contentBytes);
				for (int i = 0; i < codeOut.length; i++) {
					for (int j = 0; j < codeOut.length; j++) {
						if (codeOut[j][i]) {
							gs.fillRect(j * 3 + pixoff, i * 3 + pixoff, 3, 3);
						}
					}
				}
			} else {
				System.err.println("QRCode content bytes length = "
				+ contentBytes.length + " not in [ 0,600 ]. ");
			}
			gs.dispose();
			bufferedImage.flush();
			return bufferedImage;
			
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

	}

	public String decoderQRCode(final BufferedImage bufferedImage) {
		String decodedData = null;
		try {
			QRCodeDecoder decoder = new QRCodeDecoder();
			decodedData = new String(decoder.decode(new QRCodeImage() {
				public int getHeight() {
					return bufferedImage.getHeight();
				}
				public int getPixel(int x, int y) {
					return bufferedImage.getRGB(x, y);
				}
				public int getWidth() {
					return bufferedImage.getWidth();
				}
			}), "UTF-8");

		} catch (Exception e) {
			e.printStackTrace();
		}
		return decodedData;
	}

	/**
	 * 
	 * @param args
	 *            the command line arguments
	 */

	public static void main(String[] args) {
		String content = "Hello 大大、小小,welcome to QRCode!"
		+ "\nMyblog [ http://sjsky.iteye.com ]"
		+ "\nEMail [ sjsky007";
		Qrcoding handler = new Qrcoding();
		BufferedImage bufferedImage=handler.encoderQRCode(content);
		System.out.println("encoder QRcode success");
	        String decoderContent = handler.decoderQRCode(bufferedImage); 
	        System.out.println("解析结果如下："); 
	        System.out.println("=====================================");
	        System.out.println(decoderContent); 
	        System.out.println("=====================================");
	        System.out.println("decoder success!!!"); 

	}
}
